<template>
  <PageWrapper v-loading="loading" loading-tip="加载中...">
    <div class="p-4 p-4-tag">
      <div class="tag">
        <div class="form-box">
          <BasicForm @register="registerForm" />
        </div>
        <div class="table-box">
          <BasicTable
            @register="registerTable"
            :columns="columns"
            :dataSource="tableData"
            :canResize="false"
            :showIndexColumn="false"
            :striped="true"
            :bordered="true"
            :pagination="false"
            :actionColumn="hasPermission(['3-2-edit', '3-2-del']) ? actionColumn : undefined"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action' && hasPermission(['3-2-edit', '3-2-del'])">
                <TableAction
                  :actions="[
                    {
                      label: '编辑',
                      icon: 'ant-design:edit-outlined',
                      ifShow: hasPermission('3-2-edit'),
                      onClick: (e) => {
                        e.stopPropagation();
                        handleEdit(record);
                      },
                    },
                    {
                      label: '删除',
                      icon: 'ant-design:delete-outlined',
                      ifShow: hasPermission('3-2-del'),
                      onClick: (e) => {
                        e.stopPropagation();
                        handleDelete(record);
                      },
                    },
                  ]"
                />
              </template>
            </template>
            <template #toolbar>
              <a-button class="btn-box-item" @click="throttleReset">重置</a-button>
              <a-button class="btn-box-item" type="primary" @click="throttleSubmit">查询</a-button>
              <a-button
                type="primary"
                @click="handleShowSelect"
                v-if="hasPermission('3-2-mesAddress')"
              >
                MES地址配置
              </a-button>
              <a-button
                type="primary"
                @click="throttleSyncMesData"
                :loading="loadingByBtn"
                v-if="hasPermission('3-2-mesSynchronize')"
              >
                同步MES数据
              </a-button>
              <a-button
                class="btn-box-item"
                type="primary"
                @click="handleAdd"
                v-if="hasPermission('3-2-add')"
              >
                新增
              </a-button>
              <a-button
                type="primary"
                @click="openModalByupload"
                v-if="hasPermission('3-2-upload')"
              >
                导入
              </a-button>
              <a-button
                type="primary"
                class="btn-box-item"
                @click="handleAdd"
                v-if="hasPermission('3-2-import')"
              >
                导出
              </a-button>
            </template>
          </BasicTable>
          <div class="flex py-2 items-center justify-end pagination-box">
            <a-pagination
              :show-total="(total) => `共 ${total} 条数据`"
              showSizeChanger
              size="small"
              :current="paginationInfo.data.current"
              :pageSize="paginationInfo.data.pageSize"
              :total="paginationInfo.data.total"
              @change="handlePageChange"
            />
          </div>
        </div>
      </div>
    </div>
    <!-- 新增或编辑的弹窗 -->
    <modelByDetail
      :info="detailForm"
      @register="registerByDetail"
      @submit-success="handelUpateTable"
    />
    <!-- 上传Excel -->
    <uploadExcel
      @register="registerByUpload"
      :classParams="['SuperX.DeviceService.DeviceModel.Model.DeviceModelInfo,SuperX.DeviceService']"
      :uploadParams="{
        Controller: 'Device',
        Action: 'FileImport',
        Parameters: Parameters,
        model: 'SuperX.DeviceService.DeviceModel.Model.DeviceModelInfo,SuperX.DeviceService',
        sheetIndex: '-1',
        headRow: '0',
      }"
      @success="handleUploadSuccess"
    />
    <modelBySelect @register="registerBySelect" @submit-success="handelSuccessBySelect" />
  </PageWrapper>
</template>

<script setup lang="ts">
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { PageWrapper } from '/@/components/Page';
  import { ref, onMounted, reactive, h } from 'vue';
  import { BasicColumn } from '/@/components/Table/src/types/table';
  import { BasicTable, TableAction, useTable } from '/@/components/Table';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useModal } from '/@/components/Modal';
  import { Pagination } from 'ant-design-vue';
  import modelBySelect from '/@/views/project/equipmentLedger/components/modelBySelect.vue';
  import modelByDetail from '/@/views/project/equipmentModel/components/modelByDetail.vue';
  import { useDebounceFn } from '@vueuse/core';
  import { getdevicemodels, deldevicemodel, updateequipments } from '/@/api/equipmentModel/index';
  import uploadExcel from '/@/components/uploadExcel/index.vue';

  const throttleSyncMesData = useDebounceFn(handleSyncMesData, 500);
  const APagination = Pagination;
  const { t } = useI18n();
  const { hasPermission } = usePermission();
  let loading = ref(false);
  let loadingByBtn = ref(false);
  let tableData = reactive([]);
  let Parameters = '[""]';
  // 分页信息
  let paginationInfo = reactive({
    data: {
      pageSize: 50,
      total: 0,
      current: 1,
    },
  });
  // 表格表头
  let columns: BasicColumn[] = [
    {
      title: '型号编码',
      dataIndex: 'Code',
    },
    {
      title: '型号名称',
      dataIndex: 'Name',
    },
    // {
    //   title: '技术规格',
    //   dataIndex: 'TechnicalSpec',
    // },
    // {
    //   title: '设备类型',
    //   dataIndex: 'DeviceTypeName',
    // },
    // {
    //   title: '设备类别',
    //   dataIndex: 'DeviceTypeCategory',
    // },
    // {
    //   title: '生产厂商',
    //   dataIndex: 'Manufacturer',
    // },
  ];
  // 操作栏
  let actionColumn = {
    width: 150,
    title: '操作',
    dataIndex: 'action',
    // slots: { customRender: 'action' },
  };
  let detailForm = reactive({
    type: 'add',
    data: {},
  });
  // 表单内容
  const schemas: FormSchema[] = [
    // {
    //   field: 'searchTypeName',
    //   component: 'Input',
    //   label: '设备型号：',
    //   colProps: {
    //     span: 6,
    //   },
    // },
    {
      field: 'searchModelName',
      component: 'Input',
      label: '型号名称：',
      colProps: {
        span: 6,
      },
    },
    {
      field: 'searchModel',
      component: 'Input',
      label: '型号编码：',
      colProps: {
        span: 6,
      },
    },
    // {
    //   field: 'searchTypeCategory',
    //   component: 'Select',
    //   label: '设备类别：',
    //   colProps: {
    //     span: 6,
    //   },
    //   componentProps: {
    //     options: [
    //       { label: '全部', value: 0 },
    //       { label: '生产设备', value: 1 },
    //       { label: '检测设备', value: 2 },
    //       { label: '辅助设备', value: 3 },
    //       { label: '厂务设备', value: 4 },
    //       { label: '仪器仪表', value: 5 },
    //       { label: '办公设备', value: 6 },
    //       { label: 'IT设备', value: 7 },
    //       { label: '其它', value: 8 },
    //     ],
    //   },
    // },
  ];
  const [registerByDetail, { openModal: openModalByDetail, closeModal: closeModalByDetail }] =
    useModal();
  const [registerByUpload, { openModal: openModalByupload, closeModal: closeModalByupload }] =
    useModal();
  const [registerBySelect, { openModal: openModalBySelect, closeModal: closeModalBySelect }] =
    useModal();
  const [registerTable] = useTable();
  const { createConfirm, createMessage } = useMessage();
  const [registerForm, { validateFields, setFieldsValue }] = useForm({
    labelWidth: 100,
    schemas: schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  const throttleSubmit = useDebounceFn(handleSubmit, 500);
  const throttleReset = useDebounceFn(handleResetFields, 500);
  // 重置按钮点击事件
  async function handleResetFields() {
    setFieldsValue({
      searchModel: '',
      searchModelName: '',
      searchTypeName: '',
      searchTypeCategory: 0,
    });
    paginationInfo.data.current = 1;
    getTableData();
  }
  // 获取设备型号
  async function getTableData(params = {}) {
    try {
      loading.value = true;
      let CategoryObj = {
        1: '生产设备',
        2: '检测设备',
        3: '辅助设备',
        4: '厂务设备',
        5: '仪器仪表',
        6: '办公设备',
        7: ' IT设备',
        8: '其它',
      };
      let res = await getdevicemodels([
        {
          searchModel: '',
          searchModelName: '',
          searchTypeName: '',
          searchTypeCategory: 0,
          PageNO: paginationInfo.data.current,
          PageSize: paginationInfo.data.pageSize,
          ...params,
        },
      ]);
      paginationInfo.data.total = res.TotalRows;
      // tableData = res.Rows.map((item) => {
      //   item.DeviceTypeCategory = CategoryObj[item.DeviceTypeInfo.Category];
      //   item.DeviceTypeName = item.DeviceTypeInfo.TypeName;
      //   return item;
      // });
      tableData = res.Rows;
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  // 上传成功
  function handleUploadSuccess() {
    closeModalByupload();
    setFieldsValue({
      searchModel: '',
      searchModelName: '',
      searchTypeName: '',
      searchTypeCategory: 0,
    });
    paginationInfo.data.current = 1;
    getTableData();
  }
  // 查询按钮点击事件
  async function handleSubmit() {
    try {
      let res = await validateFields();
      console.log(`output->res`, res);
      getTableData(res);
    } catch {}
  }
  // 新增或编辑成功事件
  function handelUpateTable() {
    detailForm.type = 'add';
    detailForm.data = {};
    closeModalByDetail();
    getTableData();
  }
  // 分页事件
  function handlePageChange(page, pageSize) {
    paginationInfo.data.current = page;
    paginationInfo.data.pageSize = pageSize;
    getTableData();
  }
  // 新增
  function handleAdd() {
    detailForm.type = 'add';
    detailForm.data = {};

    openModalByDetail();
  }

  // 编辑
  function handleEdit(params) {
    detailForm.type = 'update';
    detailForm.data = params;

    openModalByDetail();
  }
  // 删除
  function handleDelete(params) {
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '温馨提示'),
      okText: '确认',
      content: () => h('span', `是否确认删除该设备（${params.ModelName}）`),
      onOk: async () => {
        loading.value = true;
        try {
          await deldevicemodel([params]);
          createMessage.success(t('layout.setting.operatingTitle'));
          getTableData();
          loading.value = false;
        } catch (error) {
          loading.value = false;
        }
      },
    });
  }
  // 显示MES地址下拉框弹窗
  function handleShowSelect() {
    openModalBySelect();
  }
  function handelSuccessBySelect() {
    closeModalBySelect();
  }
  // 同步mes数据
  async function handleSyncMesData() {
    loadingByBtn.value = true;
    try {
      await updateequipments([]);
      getTableData();
      createMessage.success('同步成功');
      loadingByBtn.value = false;
    } catch (error) {
      loadingByBtn.value = false;
    }
  }
  onMounted(async () => {
    getTableData();
  });
</script>

<style lang="less" scoped>
  .p-4-tag {
    width: 100%;
    height: 100%;
    padding: 0px !important;

    .tag {
      position: relative;
      overflow: hidden;
      height: 100%;
      background-color: #fff;

      .pagination-box {
        z-index: 9;
        padding: 10px 5px;
        box-sizing: border-box;
        position: absolute;
        width: 100%;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: #fff;
      }
    }

    .form-box {
      padding: 5px;

      ::v-deep(.ant-form-item) {
        margin: 0 5px;
        margin-bottom: 8px;
      }
    }

    .table-box {
      flex: 1;
    }

    .btn-box {
      display: flex;
      align-items: center;

      .btn-box-item {
        margin: 0 5px;
      }
    }

    .tag::after {
      content: '';
      display: block;
      width: 100%;
      height: 45px;
    }
  }

  ::v-deep .ant-col:last-child {
    .ant-form-item {
      margin-bottom: 0px;
    }
  }
</style>
